import normalizeTable, os, queryTable, json
#################################################
#################################################
#################################################
#################################################
####### Wednesday 15 February 2012
#################################################

def generateNormalisedTables(evdb, outputFile, dotOutputName):
    writeNormalisedTable(evdb, outputFile)

def writeNormalisedTable(evdb, outputFile):
    normalTable = normalizeTable.makeTable(evdb)
    htmlstring = transformTable(normalTable)

    outfile = open('output.html', 'w')
    outfile.write(htmlstring)
    outfile.close()

################################################################################
    
def generateSubtables(evdb, selectedpairs, superResults, newOutDir, metarules, prefcriterion):
    if len(superResults) == 1:
            #Then it's a standard output
            old_dir = os.getcwd()
            os.chdir(newOutDir)
            for p in selectedpairs:
                subtable = queryTable.getmysubtable(p[0],p[1],evdb)
                normalTable = normalizeTable.makeTable(subtable)
                score = getScore(p[0],p[1],superResults)
                htmlstring = "<html>"  + "\n" + "<body>"
                htmlstring = htmlstring + addArguments(p[0],p[1],subtable,normalTable,score,metarules,prefcriterion)
                htmlstring = htmlstring + transformTable(normalTable)
                #htmlstring = htmlstring + '<br><br><hr><br>'
                htmlstring = htmlstring + "</body>" + "\n" + "</html>"
                outFileName = '' + p[0] + p[1] + '.html'
                outfile = open(outFileName, 'w')
                outfile.write(htmlstring)
                outfile.close()
            os.chdir(old_dir)
    elif len(superResults) > 1:
            #Then we need to sort out our stability analysis results
            #The table is the same, the header needs to vary        
            old_dir = os.getcwd()
            os.chdir(newOutDir)
            for p in selectedpairs:
                subtable = queryTable.getmysubtable(p[0],p[1],evdb)
                normalTable = normalizeTable.makeTable(subtable)
                htmlstring = "<html>"  + "\n" + "<body>"
                scoreList = []
                argSet = set()
                for s in superResults:
					#print "Super Res", len(s), p
					score = getScore_Diff(p[0],p[1], s)
					argSet.add(addArguments(p[0],p[1], subtable, normalTable, score, metarules, prefcriterion))
                for a in argSet:
                    htmlstring = htmlstring + a
                htmlstring = htmlstring + transformTable(normalTable)
                #htmlstring = htmlstring + '<br><br><hr><br>'
                htmlstring = htmlstring + "</body>" + "\n" + "</html>"
                outFileName = '' + p[0] + p[1] + '.html'
                outfile = open(outFileName, 'w')
                outfile.write(htmlstring)
                outfile.close()
            os.chdir(old_dir)




# def generateJson(evdb, inputFilename, outputFilename, prefcriterion, metarules, superResults, newDirectory):
	# finalOutputName = "test.json" 
	# nodeSet = set()
	# for x in superResults:
		# nodeSet.add(x['T1'])
		# nodeSet.add(x['T2'])
		
	# nodeDict = {}
	# for s in nodeSet:
		# nodeDict[s] = []
	# keyNodeData = ["","",""]
	# for n in nodeDict:
		# for e in evdb:
			# if (nodeDict[n] == evdb[e]["T1"]):
				# #nodeDict[n]
			# #elif (nodeDict[n] == evdb[e]["T2"]):
				# pass
		
	
	# linkSet = set()
	
	# title = "Superiority Graph based on " + inputFilename + " under preferences: " + str(prefcriterion) + " and Meta-rules: " + str(metarules) + " Diff Analysis: Dashed lines represent a weakening under different assumptions; dotted lines represent a reversal" + '"' 
	# resDict = {"Title":title, "Nodes":{nodeSet}, "Links":{}}
	
	
	#Do this last
	#json.dump(resDict)
	#dotFileOutput = open(finalOutputName,'w')
	#pass

			
def generateDotFile(inputFilename, outputFilename, prefcriterion, metarules, superResults, newDirectory):
    finalOutputName = newDirectory + outputFilename 
    dotFileOutput = open(finalOutputName,'w')
    ##title = "Superiority Graph based on " + inputFilename + " under preferences: " + str(prefcriterion) + " and Meta-rules: " + str(metarules) + " Diff ##Analysis: Dashed lines represent a weakening under different assumptions; dotted lines represent a reversal" + '"' 
    title = ""
    print >>dotFileOutput, "digraph superioritygraph {" + "\n"
    ##print >>dotFileOutput, "labelloc = t" + "\n" + "label = " + '"' + title + '\n'

    print >>dotFileOutput, "labelloc = t" + "\n" +'\n'
    print >>dotFileOutput, generateDotArcs(superResults, newDirectory)

    print >>dotFileOutput, "}" 
    print "\n"

    dotFileOutput.close()

    

def generateDotArcs(superResults, newDir):
    outstring = ''
    quotes = '"'
    arc = '"->"'
    l = '[label = '
    extraRed = ' color="red"];'
    extraBlue = ' color="blue"];'
    endline = "\n"
    styleDotted = ' [style = dotted] '
    styleDashed= ' [style = dashed] '
    for x in superResults:
        #url = 'file:///' + newDir + '\\' + x['T1'] + x['T2'] + '.html'
        #url = 'file:// ./' + newDir + '\\' + x['T1'] + x['T2'] + '.html'
        url = newDir.lstrip('../Output') + '../' + x['T1'] + x['T2'] + '.html'
        labelURL = ' labelURL = "' + url + '"'
        #print "URL: ", url 
        meta = ', '.join(x['Metaset'])
        #print "Meta: ", meta
        evi =', '.join(x['Evidence'])
        if 'DiffRecord' in x.keys():
            if x['Direction'] == 'sup' and summariseDiff(x['DiffRecord']) == 'same':
                outstring = outstring + quotes + x['T1'] + arc + x['T2'] + quotes + l + quotes + evi + " " + meta + quotes + labelURL + extraRed + endline
            if x['Direction'] == 'sup' and summariseDiff(x['DiffRecord']) == 'weaken':
                outstring = outstring + quotes + x['T1'] + arc + x['T2'] + quotes + styleDashed + l + quotes + evi + " " + meta + quotes + labelURL + extraRed + endline
            if x['Direction'] == 'sup' and summariseDiff(x['DiffRecord']) == 'reverse':
                outstring = outstring + quotes + x['T1'] + arc + x['T2'] + quotes + styleDotted + quotes + l + quotes + evi + " " + meta + quotes + labelURL + extraRed + endline
            if x['Direction'] == 'equal':
                outstring = outstring + quotes + x['T1'] + arc + x['T2'] + quotes + l + quotes + evi + " " + meta + quotes + labelURL + " dir = both " + extraBlue + endline  
            if x['Direction'] == 'inf' and 'DiffRecord' not in x.keys():
                outstring = outstring + quotes + x['T2'] + arc + x['T1'] + quotes + l + quotes + evi + " " + meta + quotes + labelURL +  extraRed + endline
            if x['Direction'] == 'inf' and summariseDiff(x['DiffRecord']) == 'same':
                outstring = outstring + quotes + x['T2'] + arc + x['T1'] + quotes + l + quotes + evi + " " + meta + quotes + labelURL +  extraRed + endline
            if x['Direction'] == 'inf' and summariseDiff(x['DiffRecord']) == 'weaken':
                outstring = outstring + quotes + x['T2'] + arc + x['T1'] + quotes + styleDashed + l + quotes + evi + " " + meta + quotes + labelURL +  extraRed + endline    
            if x['Direction'] == 'inf' and summariseDiff(x['DiffRecord']) == 'reverse':
                outstring = outstring + quotes + x['T2'] + arc + x['T1'] + quotes + styleDotted + l + quotes + evi + " " + meta + quotes + labelURL +  extraRed + endline  

        if 'DiffRecord' not in x.keys():
            if x['Direction'] == 'sup':
                outstring = outstring + quotes + x['T1'] + arc + x['T2'] + quotes + l + quotes + evi + " " + meta + quotes + labelURL + extraRed + endline
            if x['Direction'] == 'equal':
                outstring = outstring + quotes + x['T1'] + arc + x['T2'] + quotes + l + quotes + evi + " " + meta + quotes + labelURL + " dir = both " + extraBlue + endline  
            if x['Direction'] == 'inf':
                outstring = outstring + quotes + x['T2'] + arc + x['T1'] + quotes + l + quotes + evi + " " + meta + quotes + labelURL +  extraRed + endline

    return outstring





#################################################
# Following code takes the normalized table, and produces
# the html for presenting the table
    

def transformTable(table):
    string = '<font face="arial" size="1" color="gray">' + "\n" + '<table border="1" cellpadding="10">' + "\n"
    string = string + '<tr bgcolor="lightgray">' + "\n"
    string = string + "<th>" + "EV_ID" + "</th>" + "\n"
    string = string + "<th>" + "DB_ID" + "</th>" + "\n"
    string = string + "<th>" + "TrialID" + "</th>" + "\n"
    string = string + "<th>" + "ArmA_TotalShort" + "</th>" + "\n"
    string = string + "<th>" + "ArmB_TotalShort" + "</th>" + "\n"
    string = string + "<th>" + "Outcome" + "</th>" + "\n"
    string = string + "<th>" + "Value" + "</th>" + "\n"
    string = string + "<th>" + "Direction" + "</th>" + "\n"
    string = string + "<th>" + "Significance" + "</th>" + "\n"
    string = string + "<th>" + "GRADE Result" + "</th>" + "\n"
    counter = 0
    while counter < len(table):
        x = table[counter]
        string = string + "<tr>" + "\n"
        string = string + "<td>" + str(x['normID']) + "</td>" + "\n"
        string = string + "<td>" + str(x['myid']) + "</td>" + "\n"            
        string = string + "<td>" + str(x['TrialID']) + "</td>" + "\n" 
        string = string + "<td>" + str(x['ArmA_TotalShort']) + "</td>" + "\n"
        string = string + "<td>" + str(x['ArmB_TotalShort']) + "</td>" + "\n"
        string = string + "<td>" + str(x['Outcome']) + "</td>" + "\n"
        string = string + "<td>" + str(x['Value']) + "</td>" + "\n"        
        string = string + "<td>" + str(x.get('Direction','Error')) + "</td>" + "\n"
        string = string + "<td>" + str(x.get('Significance','unknown')) + "</td>" + "\n"
        string = string + "<td>" + str(x['OverallGRADE']) + "</td>" + "\n" 
        string = string + "</tr>" + "\n"
        counter = counter+1
    #string = string + "</table>" + "\n" + "</body>" + "\n" + "</html>"
    string = string + "</table>" + "\n" 
    return string

################################################################################
################################################################################
################################################################################
################################################################################
################################################################################
################################################################################

#prefcriterion = "prefcriterion1"

#metarules = ["US","induction"]
#metarules = ["induction"]
#metarules = ["nonStatSig"]
#metarules = ["PhaseII"]
#metarules = ["StageII"]
#metarules = []



def addArguments(t1,t2,subtable,normaltable,score,metarules,prefcriterion):
    if prefcriterion == "prefcriterion1":
        return addArguments1(t1,t2,subtable,normaltable,score,metarules,prefcriterion)
    elif prefcriterion == "prefcriterion2":
        return addArguments1(t1,t2,subtable,normaltable,score,metarules,prefcriterion)    
    else: return "No results for this preference yet!"
    
def addArguments1(t1,t2,subtable,normaltable,score,metarules,prefcriterion):
    quotes = '"'
    #outstring = '<p style="background-color:gray;font-family:arial;font-size:60px;color:black;">'
    outstring = '<font face="arial" size="4" color="black">'
    outstring = outstring + '<h2>' + 'Comparison of ' + t1 + ' and ' + t2 + '</h2>'
    outstring = outstring + 'Using ' + prefcriterion + ' and metarules ' + str(metarules) + '<br><br><hr><br>'
    if score == 'sup':
        #outstring = outstring + "(Score is " + score + ")" + "<cr>"
        outstring = outstring + "<ul>"
        outstring = outstring + "<li>" + t1 + " is better than " + t2 + " because it is superior on outcomes:"
        outstring = outstring + getReason(score,t1,t2,subtable,normaltable,metarules) + "</li>" + '<br>'
        if len(getOutcomes('inf',t1,t2,subtable,normaltable,metarules)) > 0:
            outstring = outstring + "<li>" + " However, " + t2 + " is superior on outcomes:"
            outstring = outstring + getReason('inf',t1,t2,subtable,normaltable,metarules) + "</li>"
        outstring = outstring + "</ul>"
    elif score == 'equal':
        #outstring = outstring + "(Score is " + score + ")" + "<cr>"       
        outstring = outstring + t1 + " and " + t2 + " are equivalent "
        outstring = outstring + "<ul>"
        outcomesSup = getOutcomes('sup',t1,t2,subtable,normaltable,metarules)
        outcomesInf = getOutcomes('inf',t1,t2,subtable,normaltable,metarules)
        OutcomesEq = getOutcomes('equal',t1,t2,subtable,normaltable,metarules)
        if len(outcomesSup) > 0:
            outstring = outstring + "<li>" + t1 + " is superior on outcomes:"
            outstring = outstring + getReason('sup',t1,t2,subtable,normaltable,metarules) + "</li>"  + '<br>'
        if len(outcomesInf) > 0:
            outstring = outstring + "<li>" + t2 + " is superior on outcomes:"
            outstring = outstring + getReason('inf',t1,t2,subtable,normaltable,metarules) + "</li>"  + '<br>'
        if len(OutcomesEq) > 0:
            outstring = outstring + "<li>" + t1 + " and " + t2 + " are equal on outcomes:"
            outstring = outstring + getReason('equal',t1,t2,subtable,normaltable,metarules) + "</li>"
        if len(outcomesSup) == 0 and len(outcomesInf) == 0 and len(OutcomesEq) == 0:
            outstring = outstring + "<li>because of lack of appropriate evidence</li>"
        outstring = outstring + "</ul>"
    elif score == 'inf':
        #outstring = outstring + "(Score is " + score + ")" + "<cr>"
        outstring = outstring + "<ul>"
        outstring = outstring + "<li>" + t2 + " is better than " + t1 + " because it is superior on outcomes:" 
        outstring = outstring + getReason(score,t1,t2,subtable,normaltable,metarules) + "</li>" + '<br>'
        if len(getOutcomes('sup',t1,t2,subtable,normaltable,metarules)) > 0:
            outstring = outstring + "<li>" + " However, " + t1 + " is superior on outcomes:"
            outstring = outstring + getReason('sup',t1,t2,subtable,normaltable,metarules) + "</li>" + '<br>' 
        outstring = outstring + "</ul>"
    outstring = outstring + "</font>"
    #outstring = outstring + "</p>"
    return outstring

def addArguments2(t1,t2,subtable,normaltable,score,metarules,prefcriterion):
    quotes = '"'
    #outstring = '<p style="background-color:gray;font-family:arial;font-size:60px;color:black;">'
    outstring = '<font face="arial" size="4" color="black">'
    outstring = outstring + '<h2>' + 'Comparison of ' + t1 + ' and ' + t2 + '</h2>'
    outstring = outstring + 'Using ' + prefcriterion + ' and metarules ' + str(metarules) + '<br><br><hr><br>'
    if score == 'sup':
        #outstring = outstring + "(Score is " + score + ")" + "<cr>"
        outstring = outstring + "<ul>"
        outstring = outstring + "<li>" + t1 + " is better than " + t2 + " because it is superior on outcomes:"
        outstring = outstring + getReason(score,t1,t2,subtable,normaltable,metarules) + "</li>" + '<br>'
        if len(getOutcomes('inf',t1,t2,subtable,normaltable,metarules)) > 0:
            outstring = outstring + "<li>" + " However, " + t2 + " is superior on outcomes & toxicity:"
            outstring = outstring + getReason('inf',t1,t2,subtable,normaltable,metarules) + "</li>"
        outstring = outstring + "</ul>"
    elif score == 'equal':
        #outstring = outstring + "(Score is " + score + ")" + "<cr>"       
        outstring = outstring + t1 + " and " + t2 + " are equivalent "
        outstring = outstring + "<ul>"
        outcomesSup = getOutcomes('sup',t1,t2,subtable,normaltable,metarules)
        outcomesInf = getOutcomes('inf',t1,t2,subtable,normaltable,metarules)
        OutcomesEq = getOutcomes('equal',t1,t2,subtable,normaltable,metarules)
        if len(outcomesSup) > 0:
            outstring = outstring + "<li>" + t1 + " is superior on outcomes:"
            outstring = outstring + getReason('sup',t1,t2,subtable,normaltable,metarules) + "</li>"  + '<br>'
        if len(outcomesInf) > 0:
            outstring = outstring + "<li>" + t2 + " is superior on outcomes:"
            outstring = outstring + getReason('inf',t1,t2,subtable,normaltable,metarules) + "</li>"  + '<br>'
        if len(OutcomesEq) > 0:
            outstring = outstring + "<li>" + t1 + " and " + t2 + " are equal on outcomes:"
            outstring = outstring + getReason('equal',t1,t2,subtable,normaltable,metarules) + "</li>"
        if len(outcomesSup) == 0 and len(outcomesInf) == 0 and len(OutcomesEq) == 0:
            outstring = outstring + "<li>because of lack of appropriate evidence</li>"
        outstring = outstring + "</ul>"
    elif score == 'inf':
        #outstring = outstring + "(Score is " + score + ")" + "<cr>"
        outstring = outstring + "<ul>"
        outstring = outstring + "<li>" + t2 + " is better than " + t1 + " because it is superior on outcomes:" 
        outstring = outstring + getReason(score,t1,t2,subtable,normaltable,metarules) + "</li>" + '<br>'
        if len(getOutcomes('sup',t1,t2,subtable,normaltable,metarules)) > 0:
            outstring = outstring + "<li>" + " However, " + t1 + " is superior on outcomes:"
            outstring = outstring + getReason('sup',t1,t2,subtable,normaltable,metarules) + "</li>" + '<br>' 
        outstring = outstring + "</ul>"
    outstring = outstring + "</font>"
    #outstring = outstring + "</p>"
    return outstring



def getScore(left,right,superResult):
        #print str(superResult)
        #print " "
        #print superResult['T1']
        if superResult[0]['T1'] == left and superResult[0]['T2'] == right:
            return superResult[0]['Direction']
        return "error at getScore"


def getScore_Diff(left,right,superResult):
        #print str(superResult)
        #print " "
        #print superResult['T1']
        if superResult['T1'] == left and superResult['T2'] == right:
            return superResult['Direction']
        return "error at getScore"



def getReason(direction,t1,t2,subtable,normaltable,metarules):
    outcomes = getOutcomes(direction,t1,t2,subtable,normaltable,metarules)
    outstring = "<ol>"
    for outcome in outcomes:
        #print outcome
        outstring = outstring + "<li>" + str(outcome) + "</li>"
    outstring = outstring + "</ol>"
    return outstring

def getOutcomes(direction,t1,t2,subtable,normaltable,metarules):
    #print "GetOutcomes: ", direction,t1,t2,subtable,normaltable,metarules
    if metarules == []:
        return getOutcomes1(direction,t1,t2,subtable,normaltable,metarules)
    if metarules == ["nonStatSig"]:
        return getOutcomes2(direction,t1,t2,subtable,normaltable,metarules)
    if metarules == ["PhaseII"]:
        return getOutcomes3(direction,t1,t2,subtable,normaltable,metarules)
    if metarules == ["US"]:
        return getOutcomes4(direction,t1,t2,subtable,normaltable,metarules)
    if metarules == ["induction"]:
        return getOutcomes5(direction,t1,t2,subtable,normaltable,metarules)
    if metarules == ["StageII"]:
        return getOutcomes6(direction,t1,t2,subtable,normaltable,metarules)
    if metarules == ["Grade_NotGood"]:
        return getOutcomes7(direction,t1,t2,subtable,normaltable,metarules)




def getOutcomes1(direction,t1,t2,subtable,normaltable,metarules):
    supportingOutcomes = []
    for x in normaltable:
        if x['ArmA_TotalShort'] == t1 and x['ArmB_TotalShort'] == t2:
            if x.get('Direction','Error') == 'sup' and direction == 'sup':
                supportingOutcomes.append(x['Outcome'])
            elif x.get('Direction','Error') == 'inf' and direction == 'inf':
                supportingOutcomes.append(x['Outcome'])
            elif x.get('Direction','Error') == 'equal' and direction == 'equal':
                supportingOutcomes.append(x['Outcome'])
        elif x['ArmA_TotalShort'] == t2 and x['ArmB_TotalShort'] == t1:
            if x.get('Direction','Error') == 'sup' and direction == 'inf':
                supportingOutcomes.append(x['Outcome'])
            elif x.get('Direction','Error') == 'inf' and direction == 'sup':
                supportingOutcomes.append(x['Outcome'])
            elif x.get('Direction','Error') == 'equal' and direction == 'equal':
                supportingOutcomes.append(x['Outcome'])
    #print supportingOutcomes
    return supportingOutcomes


def getOutcomes2(direction,t1,t2,subtable,normaltable,metarules):
    supportingOutcomes = []
    for x in normaltable:
        if x['ArmA_TotalShort'] == t1 and x['ArmB_TotalShort'] == t2 and x.get('Significance','unknown') == 'sig':
            if x.get('Direction','Error') == 'sup' and direction == 'sup':
                supportingOutcomes.append(x['Outcome'])
            elif x.get('Direction','Error') == 'inf' and direction == 'inf':
                supportingOutcomes.append(x['Outcome'])
            elif x.get('Direction','Error') == 'equal' and direction == 'equal':
                supportingOutcomes.append(x['Outcome'])
        elif x['ArmA_TotalShort'] == t2 and x['ArmB_TotalShort'] == t1  and x.get('Significance','unknown') == 'sig':
            if x.get('Direction','Error') == 'sup' and direction == 'inf':
                supportingOutcomes.append(x['Outcome'])
            elif x.get('Direction','Error') == 'inf' and direction == 'sup':
                supportingOutcomes.append(x['Outcome'])
            elif x.get('Direction','Error') == 'equal' and direction == 'equal':
                supportingOutcomes.append(x['Outcome'])
    return supportingOutcomes


def getOutcomes3(direction,t1,t2,subtable,normaltable,metarules):
    supportingOutcomes = []
    for x in normaltable:
        if x.get('Phase','unknown') == '3':
            if x['ArmA_TotalShort'] == t1 and x['ArmB_TotalShort'] == t2:
                if x.get('Direction','Error') == 'sup' and direction == 'sup':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'inf' and direction == 'inf':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'equal' and direction == 'equal':
                    supportingOutcomes.append(x['Outcome'])
            elif x['ArmA_TotalShort'] == t2 and x['ArmB_TotalShort'] == t1:
                if x.get('Direction','Error') == 'sup' and direction == 'inf':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'inf' and direction == 'sup':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'equal' and direction == 'equal':
                    supportingOutcomes.append(x['Outcome'])
    return supportingOutcomes

def getOutcomes4(direction,t1,t2,subtable,normaltable,metarules):
    supportingOutcomes = []
    for x in normaltable:
        r = getFullRowForNormRow(x,subtable)
        geo = r.get('RecruitmentArea','unknown')
        if geo != "US":
            if x['ArmA_TotalShort'] == t1 and x['ArmB_TotalShort'] == t2:
                if x.get('Direction','Error') == 'sup' and direction == 'sup':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'inf' and direction == 'inf':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'equal' and direction == 'equal':
                    supportingOutcomes.append(x['Outcome'])
            elif x['ArmA_TotalShort'] == t2 and x['ArmB_TotalShort'] == t1:
                if x.get('Direction','Error') == 'sup' and direction == 'inf':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'inf' and direction == 'sup':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'equal' and direction == 'equal':
                    supportingOutcomes.append(x['Outcome'])
    return supportingOutcomes

def getOutcomes5(direction,t1,t2,subtable,normaltable,metarules):
    supportingOutcomes = []
    for x in normaltable:
        r = getFullRowForNormRow(x,subtable)
        ARegime = r.get('InductionChemoRegime_A','unknown')
        BRegime = r.get('InductionChemoRegime_B','unknown')
        if x['ArmA_TotalShort'] == t1 and x['ArmB_TotalShort'] == t2:
            if x.get('Direction','Error') == 'sup' and direction == 'sup' and ARegime == "None":
                supportingOutcomes.append(x['Outcome'])
            elif x.get('Direction','Error') == 'inf' and direction == 'inf' and BRegime == "None":
                supportingOutcomes.append(x['Outcome'])
            elif x.get('Direction','Error') == 'equal' and direction == 'equal' and ARegime == "None" and BRegime == "None":
                supportingOutcomes.append(x['Outcome'])
        elif x['ArmA_TotalShort'] == t2 and x['ArmB_TotalShort'] == t1:
            if x.get('Direction','Error') == 'sup' and direction == 'inf' and ARegime == "None":
                supportingOutcomes.append(x['Outcome'])
            elif x.get('Direction','Error') == 'inf' and direction == 'sup' and BRegime == "None":
                supportingOutcomes.append(x['Outcome'])
            elif x.get('Direction','Error') == 'equal' and direction == 'equal' and ARegime == "None" and BRegime == "None":
                    supportingOutcomes.append(x['Outcome'])
    return supportingOutcomes

def getOutcomes6(direction,t1,t2,subtable,normaltable,metarules):
    supportingOutcomes = []
    for x in normaltable:
        r = getFullRowForNormRow(x,subtable)
        stage = r.get('StageInfo','unknown')
        if "II" in stage:
            if x['ArmA_TotalShort'] == t1 and x['ArmB_TotalShort'] == t2:
                if x.get('Direction','Error') == 'sup' and direction == 'sup':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'inf' and direction == 'inf':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'equal' and direction == 'equal':
                    supportingOutcomes.append(x['Outcome'])
            elif x['ArmA_TotalShort'] == t2 and x['ArmB_TotalShort'] == t1:
                if x.get('Direction','Error') == 'sup' and direction == 'inf':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'inf' and direction == 'sup':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'equal' and direction == 'equal':
                    supportingOutcomes.append(x['Outcome'])
    #print "Return Outcomes: ", supportingOutcomes
    return supportingOutcomes

def getOutcomes7(direction,t1,t2,subtable,normaltable,metarules):
    supportingOutcomes = []
    for x in normaltable:
        r = getFullRowForNormRow(x,subtable)
        grade = r.get('OverallGRADE','unknown')
        if ("Good" in grade):
            if x['ArmA_TotalShort'] == t1 and x['ArmB_TotalShort'] == t2:
                if x.get('Direction','Error') == 'sup' and direction == 'sup':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'inf' and direction == 'inf':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'equal' and direction == 'equal':
                    supportingOutcomes.append(x['Outcome'])
            elif x['ArmA_TotalShort'] == t2 and x['ArmB_TotalShort'] == t1:
                if x.get('Direction','Error') == 'sup' and direction == 'inf':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'inf' and direction == 'sup':
                    supportingOutcomes.append(x['Outcome'])
                elif x.get('Direction','Error') == 'equal' and direction == 'equal':
                    supportingOutcomes.append(x['Outcome'])
    print "Return Outcomes: ", supportingOutcomes
    return supportingOutcomes


    
#################################################
# These functions have been copied from generateMetaArgs.py
# Should move them to a db query module

def getNormalizedRow(x,normTable):
    for r in normTable:
        if r.get('normID','error') == x:
            return r
    return {}

def getFullRow(i,evdb):
    for r in evdb:
        if r.get('myid','error') == i:
            return r
    return {}

def getMyId(x,normTable):
    for t in normTable:
        if t.get('normID','error') == x:
            return t.get('myid','error')
    return 'error'

#################################################
# New functions to move to a db query module


def getFullRowForNormRow(normRow,fullTable):
    i = normRow.get('myid','error')
    r = getFullRow(i,fullTable)
    return r



def simpleDiff(superGraphTuple):
    """Expects a list of SuperGraphs. It assumes that the first one ([0]) is the 'base' and generates a diff from there"""
    A = superGraphTuple[0]
    B = superGraphTuple[1]
    #Depends on notion of superGraph equality where Direction, Evidence T1 and T1 are equal
    output = []
    for a in A:
        for b in B:
                if simpleSuperComp(a,b) == 1:
                    output.append(sameSig(a))
                elif simpleSuperComp(a,b) == -1:
                    output.append(clashSig(a))
                elif simpleSuperComp(a,b) == 0:
                    output.append(weakenSig(a))
                else:
                    pass
    return superGraphTuple[0]

def simpleSuperComp(a,b):
    if a['T1'] == b['T1'] and a['T2'] == b['T2'] and a['Evidence'] == b['Evidence']:
        if a['Direction'] == b['Direction']:
            return 1
        elif (a['Direction'] == 'sup' and b['Direction'] == 'inf') or (a['Direction'] == 'inf' and b['Direction'] == 'sup'):
            return -1
        elif (a['Direction'] == 'sup' and b['Direction'] == 'equal') or (a['Direction'] == 'inf' and b['Direction'] == 'equal'):
            return 0
    else: pass
    
    
def clashSig(superGraphArc):
    o = superGraphArc
    if not 'DiffRecord' in o.keys():
        o['DiffRecord'] = []
    o['DiffRecord'].append('reverse')
    return o
    
def weakenSig(superGraphArc):
    o = superGraphArc
    if not 'DiffRecord' in o.keys():
        o['DiffRecord'] = []
    o['DiffRecord'].append('weaken')
    return o

def sameSig(superGraphArc):    
    o = superGraphArc
    if not 'DiffRecord' in o.keys():
        o['DiffRecord'] = []
    o['DiffRecord'].append('same')
    return o

def summariseDiff(listOfDiffs):
    if 'reverse' in listOfDiffs:
        return 'reverse'
    elif 'weaken' in listOfDiffs:
        return 'weaken'
    elif 'same' in listOfDiffs:
        return 'same'
    else: return 'DiffUneval'
################################################################################
################################################################################
################################################################################
################################################################################
################################################################################
################################################################################
################################################################################
################################################################################



#def transformTable(table):
#    string = "<html>"  + "\n" + "<body>" + '<basefont face="arial" size="2" color="gray">' + "\n" + '<table border="1" cellpadding="10">' + "\n"
#    tablekeys = table[0].keys()
#    string = string + "<tr>" + "\n"
#    for x in tablekeys:
#        string = string + "<th>" + x + "</th>" + "\n"
#    string = string + "</tr>" + "\n"
#    counter = 0
#    while counter < len(table):
#        entries = table[counter].values()
#        string = string + "<tr>" + "\n"
#        for x in entries:
#            string = string + "<td>" + str(x) + "</td>" + "\n"
#        string = string + "</tr>" + "\n"
#        counter = counter+1
#    string = string + "</table>" + "\n" + "</body>" + "\n" + "</html>"
#    return string

#################################################
#################################################


#myindent = "   "

#myindent2 = myindent + myindent

#outstring = "<evidence>" + "\n"

#for x in subtable:
#    outstring = outstring + myindent + "<item>" + "\n"
#    outstring = outstring + myindent2 + "<myid>" + str(x['myid']) + "</myid>" + "\n"
#    outstring = outstring + myindent2 + "<treatmentA>" + x.get('ArmA_TotalShort',"null") + "</treamentA>" + "\n"
#    outstring = outstring + myindent2 + "<treatmentB>" + x.get('ArmB_TotalShort',"null") + "</treamentB>" + "\n"
#    outstring = outstring + myindent2 + "<1YrRiskRatio>" + x.get('1YrRiskRatio',"null") + "</1YrRiskRatio>" + "\n"
#    outstring = outstring + myindent2 + "<2YrRiskRatio>" + x.get('2YrRiskRatio',"null") + "</2YrRiskRatio>" + "\n"
#    outstring = outstring + myindent2 + "<3YrRiskRatio>" + x.get('3YrRiskRatio',"null") + "</3YrRiskRatio>" + "\n"
#    outstring = outstring + myindent + "</item>" + "\n"

#outstring = outstring + "</evidence>" + "\n"
#################################################
#################################################
